<template>
  <div class="op-container">
    <k-button v-if="authorityHandle(26)" class="top-btn" value="添加箱子" @click.native="addBoxDialog" />
    <!-- <k-button class="top-btn" value="玩法介绍" @click.native="ruleGuideDialog" /> -->
    <div class="top-right-btn">
      <k-button value="设置" @click.native="gradeSettingDialog" />
    </div>
    <!--表格相关 -->
    <el-table
      ref="dragTable"
      :data="gradeBoxList"
      fit
      border
      row-key="id"
      highlight-current-row
      style="width: 100%;border-radius:8px;"
      :header-cell-style="{background:'#F6F5FA',color:'#4E4F62'}"
    >
      <el-table-column type="index" label="序号" width="60px" align="center" />
      <el-table-column min-width="150px" label="箱子图标" align="center">
        <template slot-scope="scope">
          <KImage :imagevalue="scope.row.imgUrl" width-item="50px" height-item="50px" />
        </template>
      </el-table-column>
      <el-table-column prop="boxName" min-width="100px" label="箱子名称" align="center" show-overflow-tooltip />
      <el-table-column prop="grade" min-width="80px" label="箱子等级" align="center" show-overflow-tooltip />
      <el-table-column
        prop="rechargeInterval"
        min-width="100px"
        label="消费区间"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column min-width="150px" label="饰品缩略图" align="center">
        <template slot-scope="scope">
          <KImage :imagevalue="scope.row.goodsImgUrl" width-item="110px" height-item="80px" />
        </template>
      </el-table-column>

      <el-table-column min-width="150px" label="等级头像框" align="center">
        <template slot-scope="scope">
          <KImage :imagevalue="scope.row.iconUrl" width-item="110px" height-item="80px" />
        </template>
      </el-table-column>

      <el-table-column min-width="200px" label="操作" align="center">
        <template slot-scope="scope">
          <div class="op-div">
            <k-button
              v-if="authorityHandle(26)"
              class="table-btn"
              value="修改"
              @click.native="addBoxUpdateDialog(scope.row)"
            />
            <k-button class="table-btn" value="配置饰品" @click.native="configBabyLib(scope.row.id,26)" />
            <!-- :disabled="scope.row.boxStatus === 1 ? true : false" -->
            <k-button
              v-if="authorityHandle(26)"
              class="table-btn"
              value="删除"
              @click.native="deleteBox(scope.row.id)"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column min-width="200px" label="上架状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.boxStatus"
            :disabled="!authorityHandle(26)"
            active-color="#3b425d"
            inactive-color="#E9EBF2"
            active-text="上架"
            inactive-text="下架"
            :active-value="1"
            :inactive-value="2"
            @change="boxOnlineState($event,scope)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加箱子 弹窗 -->
    <k-dialog
      :show-hide.sync="addBox.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="添加箱子"
      class="addBox-dialog"
      :show-foot="false"
      :two-btn="true"
      @click="saveGradeData"
    >
      <el-form :model="addBoxInfo" label-width="auto" class="form-modify">
        <el-form-item label="箱子名称：">
          <el-input v-model="addBoxInfo.boxName" show-word-limit placeholder="请输入箱子名称" />
        </el-form-item>
        <el-form-item label="箱子图标：" prop="iconUrl">
          <k-upload-file
            ref="upload1"
            v-model="addBoxInfo.imgUrl"
            upload-style="img"
            @successUpload="successUpload($event,0)"
          />
          <span style="color: #b2b2b2">只能上传jpg/png文件，且不超过2M</span>
        </el-form-item>
        <el-form-item label="箱子等级：">
          <el-select v-model="addBoxInfo.grade" placeholder="请选择等级" @change="getGradeOne">
            <el-option
              v-for="item in gradeOptions"
              :key="item.lineId"
              :label="item.lineName"
              :value="item.lineId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="消费区间：">
          <el-input v-model="addBoxInfo.minRecharge" disabled class="price-input" />
          <i style="margin: 0 3px;"> — </i>
          <el-input v-model="addBoxInfo.maxRecharge" disabled class="price-input" />
        </el-form-item>
        <el-form-item label="等级头像框：">
          <el-select v-model="addBoxInfo.iconId" placeholder="请选择头像">
            <el-option
              v-for="item in iconsResultList"
              :key="item.lineId"
              :label="item.lineName"
              :value="item.lineId"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </k-dialog>
    <!-- addBox 修改弹窗 -->
    <k-dialog
      :show-hide.sync="addBoxUpdate.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      class="addBox-dialog"
      title="修改箱子"
      :show-foot="false"
      :two-btn="true"
      @click="saveGradeData"
    >
      <el-form :model="addBoxInfo" label-width="auto" class="form-modify">
        <el-form-item label="箱子名称：">
          <el-input v-model="addBoxInfo.boxName" show-word-limit placeholder="请输入箱子名称" />
        </el-form-item>
        <el-form-item label="箱子图标：">

          <k-upload-file
            ref="upload1"
            v-model="addBoxInfo.imgUrl"
            upload-style="img"
            @successUpload="successUpload($event,0)"
          />
          <span style="color: #b2b2b2">只能上传jpg/png文件，且不超过2M</span>
        </el-form-item>
        <el-form-item label="箱子等级：">
          <el-select v-model="addBoxInfo.grade" placeholder="请选择等级" @change="getGradeOne">
            <el-option
              v-for="item in gradeOptions"
              :key="item.lineId"
              :label="item.lineName"
              :value="item.lineId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="饰品展示缩略图：">
          <k-upload-file
            ref="upload2"
            v-model="addBoxInfo.goodsImgUrl"
            upload-style="img"
            @successUpload="successUpload($event,1)"
          />
          <span style="color: #b2b2b2">只能上传jpg/png文件，且不超过2M</span>
        </el-form-item>

        <el-form-item label="消费区间：">
          <el-input v-model="addBoxInfo.minRecharge" disabled class="price-input" />
          <i style="margin: 0 3px;"> — </i>
          <el-input v-model="addBoxInfo.maxRecharge" disabled class="price-input" />
        </el-form-item>
        <el-form-item label="等级头像框：">
          <el-select v-model="addBoxInfo.iconId" placeholder="请选择头像">
            <el-option
              v-for="item in iconsResultList"
              :key="item.lineId"
              :label="item.lineName"
              :value="item.lineId"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </k-dialog>

    <!-- 玩法介绍 弹窗 -->
    <k-dialog
      :show-hide.sync="ruleGuide.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="玩法介绍"
      class-name="ruleGuide-dialog"
      :show-foot="false"
      :two-btn="authorityHandle(26)"
      @click="guideSave"
    >
      <div class="dialog-ruleGuide" style="padding:30px">
        <el-form :model="ruleGuideContent" label-width="auto">
          <el-form-item label="内容介绍：" prop="content">
            <quill-editor
              ref="myQuillEditor"
              v-model.trim="ruleGuideContent.content"
              :options="editorOption"
              class="editer"
            />
          </el-form-item>
        </el-form>
      </div>
    </k-dialog>
    <!-- 设置 弹窗 -->
    <k-dialog
      :show-hide.sync="gradeSetting.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="设置"
      :show-foot="false"
      :two-btn="authorityHandle(26)"
      :close-fun="gradeSettingDialogClose"
      @click="saveGradeSetting"
    >
      <div class="dialog-warningSetting">
        <span class="warning-title">每日衰减金额：</span>
        <el-input
          v-model="gradeSettingModel.decayPrice"
          :readonly="!authorityHandle(26)"
          onkeyup="value=value.replace(/[^0-9.]/g,'')"
          style="width:150px"
          clearable
        />
        <ul>
          <li v-for="(gradeItem, index) in gradeSettingModel.gradeList" :key="gradeItem.id">
            <span class="warning-title">等级：</span>
            <el-input
              v-model="gradeItem.grade"
              :readonly="!authorityHandle(26)"
              onkeyup="value=value.replace(/[^0-9.]/g,'')"
              clearable
            />
            <span class="warning-title-right">流水范围：</span>
            <el-input
              v-model="gradeItem.minRecharge"
              :readonly="!authorityHandle(26)"
              onkeyup="value=value.replace(/[^0-9.]/g,'')"
              class="price-input"
            />
            <i style="margin: 0 3px;"> — </i>
            <el-input
              v-model="gradeItem.maxRecharge"
              :readonly="!authorityHandle(26)"
              onkeyup="value=value.replace(/[^0-9.]/g,'')"
              class="price-input"
            />
            <span class="warning-title-right">流水激励：</span>
            <el-input
              v-model="gradeItem.flowingIncentives"
              :readonly="!authorityHandle(26)"
              onkeyup="value=value.replace(/[^0-9.]/g,'')"
              class="price-input"
            />
            <span>%</span>

            <i
              v-if="authorityHandle(26)"
              v-show="index != 0"
              class="el-icon-remove"
              @click="removeGradeItem(gradeItem.id)"
            />
            <i
              v-if="authorityHandle(26)"
              v-show="index === gradeSettingModel.gradeList.length-1"
              class="el-icon-circle-plus"
              @click="addGradeItem"
            />
          </li>
        </ul>
      </div>
    </k-dialog>
  </div>
</template>

<script>
import {
  updateBoxUpStatus,
  getGradeBoxDescribe,
  setGradeBoxDescribe,
  getGradeSetting,
  setGradeSetting,
  getGradeList,
  getGradeOne,
  saveGradeData,
  listGradeData,
  updateGradeSort,
  deleteGradeData
} from '@/api/rules/listdata'
import {
  getNormalIconFrame
} from '@/api/activity'

import Sortable from 'sortablejs'
export default {
  data() {
    return {
      ruleGuideContent: {
        content: ''
      },
      ruleGuide: {
        showHide: false
      },
      gradeOptions: [],
      iconsResultList: [],
      addBoxInfo: {
        id: '',
        boxName: '',
        imgUrl: '',
        grade: '',
        minRecharge: '',
        maxRecharge: '',
        iconId: ''
      },
      addBox: {
        showHide: false
      },
      addBoxUpdate: {
        showHide: false
      },
      gradeSettingModel: {
        gradeList: [{
          id: undefined,
          grade: undefined,
          minRecharge: '',
          maxRecharge: '',
          flowingIncentives:''
        }],
        decayPrice: ''
      },
      editorOption: { //  富文本编辑器配置
        placeholder: '请输入内容',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'], // 引用，代码块
            [{
              'header': 1
            }, {
              'header': 2
            }], // 标题，键值对的形式；1、2表示字体大小
            [{
              'list': 'ordered'
            }, {
              'list': 'bullet'
            }], // 列表
            [{
              'script': 'sub'
            }, {
              'script': 'super'
            }], // 上下标
            [{
              'indent': '-1'
            }, {
              'indent': '+1'
            }], // 缩进
            [{
              'direction': 'rtl'
            }], // 文本方向
            [{
              'size': ['small', false, 'large', 'huge']
            }], // 字体大小
            [{
              'header': [1, 2, 3, 4, 5, 6, false]
            }], // 几级标题
            [{
              'color': []
            }, {
              'background': []
            }], // 字体颜色，字体背景颜色
            [{
              'font': []
            }], // 字体
            [{
              'align': []
            }], // 对齐方式
            ['clean'], // 清除字体样式
            ['image'] // 上传图片、上传视频
          ]
        }
      },
      gradeSetting: {
        showHide: false
      },
      gradeBoxList: [],
      sortable: null
    }
  },
  created() {
    this.getList()
    this.getGradeList()
    this.getGeneralDescribe()
  },
  methods: {
    // 等级箱子列表页加载数据
    getList() {
      listGradeData().then(res => {
        this.gradeBoxList = res.data
        this.$nextTick(() => {
          this.setSort()
        })
      })
    },
    setSort() {
      const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.gradeBoxList.splice(evt.oldIndex, 1)[0]
          this.gradeBoxList.splice(evt.newIndex, 0, targetRow)
          this.gradeBoxList.map((item, index) => {
            item.zoneSort = index
          })
          // 等级箱子列表页更新排序
          updateGradeSort(this.gradeBoxList).then(res => {
            this.$log(res)
          })
        }
      })
    },
    // 保存玩法管理
    guideSave() {
      const contents = this.ruleGuideContent.content
      setGradeBoxDescribe({
        'data': contents
      }).then(res => {
        this.ruleGuide.showHide = false
      })
    },
    // 加载玩法管理
    getGeneralDescribe() {
      getGradeBoxDescribe().then(res => {
        this.ruleGuideContent.content = res.data
      })
    },
    addBoxDialog() {
      this.getGradeSetting()
      getNormalIconFrame().then(res => {
        this.iconsResultList = res.data
      })
      this.addBox.showHide = true
      this.$resetForm(this.addBoxInfo)
    },
    addBoxUpdateDialog(row) {
      this.$resetForm(this.addBoxInfo)
      getNormalIconFrame().then(res => {
        this.iconsResultList = res.data
      })
      this.addBoxUpdate.showHide = true
      this.addBoxInfo.id = row.id
      this.addBoxInfo.grade = row.grade
      this.addBoxInfo.boxName = row.boxName
      this.addBoxInfo.imgUrl = row.imgUrl
      this.addBoxInfo.goodsImgUrl = row.goodsImgUrl
      this.addBoxInfo.iconId = row.iconId
      this.getGradeOne(row.grade)
    },
    deleteBox(boxid) {
      this.$confirm('确定要删除该箱子么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteGradeData({
          'id': boxid
        }).then(res => {
          if (res.data.success) {
            this.$message.success('操作成功')
            this.getList()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {

      })
    },
    // 箱子上架
    boxOnlineState(event, scope) {
      const id = scope.row.id
      updateBoxUpStatus({
        'id': id
      }).then(res => {
        this.$log(res)
      })
    },
    // 跳转配置饰品
    configBabyLib(boxid, permission) {
      this.$router.push({
        path: '/rootplayrules/config-babylibnew',
        query: {
          id: boxid,
          permissionid: permission
        }
      })
    },

    // 添加|修改等级箱子
    saveGradeData() {
      this.$log(this.addBoxInfo)
      saveGradeData(this.addBoxInfo).then(res => {
        if (res.data.success) {
          this.$message.success('操作成功')
          this.getList()
        } else {
          this.$message.error(res.data.msg)
        }
        this.$resetForm(this.addBoxInfo)
        this.addBox.showHide = false
        this.addBoxUpdate.showHide = false
      })
    },
    getGradeList() {
      getGradeList().then(res => {
        Object.assign(this.gradeOptions, res.data)
      })
    },
    getGradeOne(item) {
      getGradeOne({
        'grade': item
      }).then(res => {
        this.addBoxInfo.minRecharge = res.data.minRecharge
        this.addBoxInfo.maxRecharge = res.data.maxRecharge
      })
    },
    gradeSettingDialogClose() {

    },
    // 获取等级设置详情
    getGradeSetting() {
      getGradeSetting().then(res => {
        Object.assign(this.gradeSettingModel, res.data)
        // this.$log(this.gradeSettingModel)
      })
    },
    // 保存等级箱子设置
    saveGradeSetting() {
      this.$log(this.gradeSettingModel)
      setGradeSetting(this.gradeSettingModel).then(res => {
        this.$log(res)
        this.gradeSetting.showHide = false
      }).catch(error => {
        this.$log(error)
        this.$message.error('保存出错')
      })
    },
    // 移除等级
    removeGradeItem(value) {
      const index = this.gradeSettingModel.gradeList.findIndex(function(item) {
        return item.id === value
      })
      if (index !== -1) {
        this.gradeSettingModel.gradeList.splice(index, 1)
      }
    },
    addGradeItem() {
      this.gradeSettingModel.gradeList.push({
        id: undefined,
        grade: undefined,
        minRecharge: '',
        maxRecharge: ''
      })
    },
    ruleGuideDialog() {
      this.ruleGuide.showHide = true
    },

    gradeSettingDialog() {
      this.getGradeSetting()
      this.gradeSetting.showHide = true
    },
    successUpload(data, flag) {
      if (flag === 0) {
        this.addBoxInfo.imgUrl = data
      } else {
        this.addBoxInfo.goodsImgUrl = data
      }
    }
  }
}
</script>
<style>
	.sortable-ghost {
		opacity: .8;
		color: #fff !important;
		background: #3b425d !important;
	}
</style>
<style lang="scss" scoped>
	$mainColor:#3b425d; // 主色调
	$disabledColor: #909399; //禁用色
	$hoverColor:#1D143C; // 鼠标停留主色调浅色

	.op-container {
		margin: 20px;
	}

	.top-btn {
		margin: 10px 0px 30px 0px;
		font-size: 14px;
		color: #ffffff;

		&:nth-of-type(2) {
			margin-left: 10px;
		}
	}

	.top-right-btn {
		position: absolute;
		right: 20px;
		top: 30px;

		::v-deep .el-button {
			background-color: #F8F7FB;
			border-color: transparent;
			color: #14162E;

			&:hover {
				color: #ffffff;
				background-color: $mainColor;
			}

			&:active {
				color: #14162E;
			}
		}
	}

	::v-deep .el-select .el-input.is-focus .el-input__inner {
		border-color: $mainColor;
	}

	::v-deep .el-input__inner:focus {
		border-color: $mainColor;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	.price-input {
		width: 70px;
	}

	.addBox-dialog {
		::v-deep .el-dialog__body {
			padding: 10px 80px;
		}

		::v-deep .image-slot {
			display: flex;
			justify-content: center;
			align-items: center;
			width: 100%;
			height: 100%;
			background: #f5f7fa;
			color: #909399;
			font-size: 40px;
		}
	}

	.upload-btn {
		font-size: 14px;
		color: #ffffff;
	}

	.editer {
		border-radius: 8px;
		float: left;
		box-sizing: border-box;
		color: #606266;

		::v-deep .ql-container {
			height: 440px;
			border-radius: 0px 0px 8px 8px;
		}

		::v-deep .ql-toolbar.ql-snow {
			border-radius: 8px 8px 0px 0px;
		}
	}

	.dialog-warningSetting {
		::v-deep.el-input {
			width: 110px;
		}

		.price-input {
			width: 100px;
		}

		.el-icon {

			&-circle-plus,
			&-remove {
				font-size: 22px;
				color: #3b425d;
				margin-left: 10px;

			}
		}

		ul {
			list-style-type: none;
			margin-top: 20px;
			padding: 0;

			li {
				margin: 0 0 30px 0px;
				display: flex;
				flex-direction: row;
				align-items: center;

				i {
					color: #D1D5DD;
				}
			}
		}

		.warning-title {
			font-size: 16px;
			color: #14162E;

			&-right {
				font-size: 16px;
				color: #14162E;
				margin-left: 80px;
			}

			&-right2 {
				font-size: 16px;
				color: #14162E;
				margin-left: 20px;
			}
		}
	}

	.table-btn {
		width: 90px;
		height: 35px;
		line-height: 35px;
		padding: 0;
		background: #e7ecf8;
		border: 1px solid $mainColor;
		border-radius: 8px;
		font-size: 14px;
		color: $mainColor;

		&:hover {
			background: $mainColor;
			color: #fff;
		}

		&:focus {
			background-color: #e7ecf8;
		}
	}
</style>
